import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:settings_ui/settings_ui.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/setting/dialog/command_dialog_interface.dart';
import 'package:tracker/pages/home/setting/dialog/custom_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/deep_sleep_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/light_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/location_interval_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/location_priority_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/low_voltage_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/offline_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/over_speed_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/power_off_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/simple_command_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/vibration_alarm_dialog.dart';
import 'package:tracker/pages/home/setting/dialog/work_mode_dialog.dart';
import 'package:tracker/pages/home/setting/model/get_setting_resp.dart';
import 'package:tracker/pages/home/setting/model/remote_setting_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/toast_utils.dart';

import '../../../../common/constants/app_constants.dart';
import '../../../../common/permission/permission_manager.dart';
import '../../home/model/home_device_info_resp.dart';
import '../../record_history/model/device_details_resp.dart';
import '../../record_history/model/read_file_resp.dart';

/// 设置 页面
class RemoteSettingPage extends ConsumerStatefulWidget {
  const RemoteSettingPage({super.key});

  @override
  ConsumerState<RemoteSettingPage> createState() => _SettingPageState();
}

class _SettingPageState extends ConsumerState<RemoteSettingPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  List<RemoteSettingData> remoteSettingList = [];
  DeviceDetails? deviceDetails;

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      _fetchSettingList();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  _fetchSettingList() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
    };
    final res = await get<RemoteSettingListResp, RemoteSettingListResp>('/command/list',
        queryParameters: queryParams, decodeType: RemoteSettingListResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        // 过滤某些指令
        final noFilterList = [
          'nmset',
          'c',
          'nmdw',
          'senalm',
          'offline',
          'timer',
          'exbatalm',
          'speed',
          'wake',
          'flytime',
          'reset',
          'common'
        ];
        final settingList =
            resp.data?.where((element) => noFilterList.contains(element.cmdCode?.toLowerCase())).toList();
        // 更新数据
        // for (var setting in settingList ?? []) {
        //   if (setting.cmdName == "远程开关机") {
        //     setting.cmdName = "远程开关机";
        //     setting.remark = "远程关机后不能定位拾音，没有轨迹，无法远程指令控制，减少电量损耗。设置远程关机/开机，3分钟生效";
        //     setting.cmdFormat = setting.cmdFormat.replaceAll("远程开机", "远程开启");
        //     setting.cmdFormat = setting.cmdFormat.replaceAll("远程关机", "远程关机");
        //   }
        //   if (setting.cmdName == "工作模式") {
        //     setting.cmdName = "定位模式";
        //   }
        //   XLogger.info('${setting.cmdFormat}');
        // }
        setState(() {
          remoteSettingList = settingList ?? [];
        });
      } else {
        ToastUtils.showToast(resp.msg ?? '获取远程设置列表失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取远程设置列表失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取远程设置列表失败: msg: $msg, code: $code');
    });
  }

  Widget _buildSettingList() {
    return ListView.separated(
      shrinkWrap: true,
      physics: const ScrollPhysics(),
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(remoteSettingList[index].cmdName ?? ''),
          subtitle: Text(remoteSettingList[index].introduction ?? ''),
          trailing: const Icon(Icons.arrow_forward_ios),
          onTap: () {
            final remoteSettingData = remoteSettingList[index];
            _onListItemTap(remoteSettingData);
          },
        );
      },
      separatorBuilder: (context, index) {
        return const Divider(
          height: 1,
        );
      },
      itemCount: remoteSettingList.length,
    );
  }



  /// 点击指令
  _onListItemTap(RemoteSettingData remoteSettingData) async {

    XLogger.info('点击指令: ${remoteSettingData.cmdName}，指令编码：${remoteSettingData.cmdCode}');
    CommandDialogInterface? commandDialogInterface;
    final deviceInfo = ref.read(deviceInfoProvider);

    switch (remoteSettingData.cmdCode!.toLowerCase()) {
      case 'nmset':

        final deviceInfo = ref.watch(deviceInfoProvider);
        final res = await get<DeviceDetailsResp, DeviceDetailsResp>(
            '$newBaseULr/device/${deviceInfo.imei}',
            decodeType: DeviceDetailsResp());
        res.when(success: (resp) {
          deviceDetails = resp.data;
          // 工作模式
          commandDialogInterface = WorkModeDialog(
              scaffoldKey: _scaffoldKey, cmdCode: remoteSettingData.cmdCode, onConfirm: _onSendCommandClickCallback, onchooseModeConfirm: _onchooseModeConfirmCallback, imei: deviceInfo.imei, deviceDetails: resp.data);
        }, failure: (String msg, int code) {
          XLogger.error('获取设备信息失败：msg: $msg, code: $code');
          deviceDetails = DeviceDetails();
        });

        break;
      case 'c':
        // 立即定位
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'nmdw':
        // 定位优先级
        commandDialogInterface = LocationPriorityDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'senalm':
        // 震动报警
        commandDialogInterface = VibrationAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'factory':
        // 恢复出厂设置
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'factoryall':
        // 恢复出厂设置（所有参数）
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'offline':
        // 远程开关机
        commandDialogInterface = OfflineDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'timer':
        // 定位间隔
        commandDialogInterface = LocationIntervalDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'poweralm':
        // 断电报警
        commandDialogInterface = PowerOffAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'exbatalm':
        // 低电压报警
        commandDialogInterface = LowVoltageAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'speed':
        // 超速报警
        commandDialogInterface = OverSpeedAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'lightalm':
        // 光感报警
        commandDialogInterface = LightAlarmDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'wake':
        // 立即定位(唤醒)
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'flytime':
        // 深度休眠
        commandDialogInterface = DeepSleepDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'reset':
        // 远程重启
        commandDialogInterface = SimpleCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      case 'common':
        // 文本指令下发
        commandDialogInterface = CustomCommandDialog(
            scaffoldKey: _scaffoldKey, remoteSettingData: remoteSettingData, onConfirm: _onSendCommandClickCallback);
        break;
      default:
        ToastUtils.showToast('暂不支持该指令');
        break;
    }
    // 获取用户指令配置
    final userSettingRes = await _getUserSetting(remoteSettingData.cmdCode!);
    userSettingRes.when(success: (resp) async {
      if (resp.code == 200) {
        if (remoteSettingData.cmdCode!.toLowerCase() == 'nmset') {
          final res1 = await get<BaseResp, BaseResp>('$newBaseULr/device/model/list?imei=${deviceInfo.imei}',decodeType: BaseResp());
          res1.when(success: (resp1) {

            ToastUtils.dismissLoading();
            if (resp1.code == 200) {
              XLogger.info("commandDialogInterface?.show");

              commandDialogInterface?.updateCmdContent((resp.data?.cmdContent ?? '') + ',' + resp1.data.toString());
              commandDialogInterface?.show(context);
            }
            }, failure: (String msg, int code) {
            XLogger.error('发送指令失败: msg: $msg, code: $code');
          });
        }else {
          commandDialogInterface?.updateCmdContent(resp.data?.cmdContent ?? '');
          commandDialogInterface?.show(context);
        }
      } else {
        ToastUtils.showToast(resp.msg ?? '获取用户指令配置失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('获取用户指令配置失败: msg: $msg, code: $code');
      ToastUtils.showToast('获取用户指令配置失败: msg: $msg, code: $code');
    });
  }

  Future<Result<GetSettingResp>> _getUserSetting(String cmdCode) async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'cmdCode': cmdCode,
    };
    final res =
        await post<GetSettingResp, GetSettingResp>('/command/getSetting', data: postData, decodeType: GetSettingResp());
    return res;
  }


  _onchooseModeConfirmCallback(int switchValue) async {
    final deviceInfo = ref.read(deviceInfoProvider);
    deviceInfo.deviceMode = switchValue;
  }

  _onSendCommandClickCallback(String cmdContent) async {
    XLogger.info('发送指令: $cmdContent');
    final deviceInfo = ref.read(deviceInfoProvider);
    final postData = {
      'imei': deviceInfo.imei,
      'content': cmdContent,
      'cmdCode': cmdContent.split(',')[0],
    };
    ToastUtils.showLoading(status: '发送中...');
    final res = await post<BaseResp, BaseResp>('/command/send', data: postData, decodeType: BaseResp());
    res.when(success: (resp) async {
      ToastUtils.dismissLoading();
      if (resp.code == 200) {
        // 如果是定位模式
        if (cmdContent.split(',')[0] == "nmset"){
          int switchValue = deviceInfo.deviceMode ?? -1;
          final data = {
            "imei": deviceInfo.imei,
            "positionStatus": "1"
          };
          if (switchValue == 3) {
            setDevice(data: data, voidCallback: () {
              _onSendModeCommandClick(deviceInfo.imei??"", switchValue, (){
                ToastUtils.showToast('发送成功');

              }, (){
                ToastUtils.showToast('存储模式失败');
              });
            });
          }else {
            _onSendModeCommandClick(deviceInfo.imei??"", switchValue, (){
              ToastUtils.showToast('发送成功');

            }, (){
              ToastUtils.showToast('存储模式失败');
            });
          }


        }else {
          ToastUtils.showToast('发送成功');
        }

        // 如果是远程关闭 ，就在发送一个 db,0
        // if (cmdContent.split(',')[0] == "Offline" && cmdContent.split(',')[1] == "1") {
        //   final postData = {
        //     'imei': deviceInfo.imei,
        //     'content': "db,0",
        //     'cmdCode': "db",
        //   };
        //
        //   final res =
        //       await post<ReadFileResp, ReadFileResp>('/command/send',
        //       data: postData,
        //       decodeType: ReadFileResp());
        //   res.when(success: (resp) async {
        //     final res =
        //     await post<ReadFileResp, ReadFileResp>('$newBaseULr/device/command',
        //         data: {'imei':deviceInfo.imei,'securityStatus':'0'},
        //         decodeType: ReadFileResp());
        //     res.when(success: (resp) async {
        //       ToastUtils.showToast('发送成功');
        //
        //     }, failure: (String msg, int code) {
        //       ToastUtils.dismissLoading();
        //       XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
        //       return ReadFileResp();
        //     });
        //
        //   }, failure: (String msg, int code) {
        //     ToastUtils.dismissLoading();
        //     XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
        //     return ReadFileResp();
        //   });
        // }else {

        // }

      } else {
        ToastUtils.showToast(resp.msg ?? '发送失败');
      }
    }, failure: (String msg, int code) {
      XLogger.error('发送指令失败: msg: $msg, code: $code');
      ToastUtils.showToast('发送指令失败: msg: $msg, code: $code');
    });

  }

  @override
  Widget build(BuildContext context) {
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: const Text(
          '远程设置',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        backgroundColor: AppTheme.themeConfig.primaryColor,
        leading: GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: const Icon(
              Icons.arrow_back,
              color: Colors.white,
              size: 24,
            )),
      ),
      child: Column(
        children: [
          _buildSettingList(),
        ],
      ),
    );
  }

  // 服务器2  模式指令存储
  _onSendModeCommandClick(String imei,int switchValue,Function() success,Function() fail) async{
    // final deviceInfo = ref.read(deviceInfoProvider);
    // XLogger.info('获取用户指令配置');

    final res = await get<BaseResp, BaseResp>('$newBaseULr/device/model/update?imei=${imei}&value=$switchValue',decodeType: BaseResp());
    res.when(success: (resp) {
      // ToastUtils.dismissLoading();
      if (resp.code == 200) {
        success();
      } else {
        fail();
      }
    }, failure: (String msg, int code) {
      fail();
      XLogger.error('发送指令失败: msg: $msg, code: $code');
    });
  }

  setDevice({required dynamic data, VoidCallback? voidCallback}) async {
    XLogger.info(data);
    XLogger.info('${deviceDetails?.deviceName}');
    if (deviceDetails?.securityVip == 1) {
    } else {}

    ToastUtils.showLoading(status: "处理中...");
    final res =
    await post<ReadFileResp, ReadFileResp>('$newBaseULr/device/command',
        data: data,
        decodeType: ReadFileResp());
    res.when(success: (resp) async {
      if(voidCallback != null){
        voidCallback();
      }
    }, failure: (String msg, int code) {
      ToastUtils.dismissLoading();
      XLogger.error('设备录音文件已读失败：msg: $msg, code: $code');
      return ReadFileResp();
    });
  }


}
